<template>
	<a-input-group compact class="global-condition-search">
		<a-select
			v-show="props.searchSelects.length > 1"
			:value="searchState.selectValue"
			:dropdown-match-select-width="false"
			:label-in-value="true"
			:options="props.searchSelects"
			:get-popup-container="
				(triggerNode: any) => {
					return triggerNode.parentNode;
				}
			"
			@change="ChangeSelect"
		/>

		<a-input v-model:value="searchState.inputValue" :style="cInput.style" :placeholder="cInput.placeholder" @keyup.enter="Search" />

		<div class="search-btn-wrap" @click="Search">
			<global-svg-icon icon-name="search" width="12px" height="12px" />
		</div>
	</a-input-group>
</template>

<script setup lang="ts" name="GlobalConditionSearch">
import { reactive, computed, watch, nextTick } from 'vue';

type TsProps = {
	// 输入框宽度
	inputWidth?: number;
	// 多种搜索条件
	searchSelects: TsSelectOption[];
	// 列表的搜索条件对象, 一般来自 $list.hooks中
	searchQuery: Record<string, any>;
};
type TsSearchState = {
	// 当前选中的搜索条件
	selectValue: TsSelectOption;
	// 当前Input输入的搜索值
	inputValue: string;
};

const props = withDefaults(defineProps<TsProps>(), {
	inputWidth: 328,
	searchQuery: () => ({}),
	searchSelects: () => []
});

const emits = defineEmits<{
	(e: 'search'): void;
	(e: 'update:searchQuery', newSearchQuery: Record<string, any>): void;
}>();

const searchState = reactive<TsSearchState>({
	selectValue: props.searchSelects.length ? props.searchSelects[0] : { label: '', value: '' },
	inputValue: ''
});

const cInput = computed(() => {
	return {
		style: { width: `${props.inputWidth}px` },
		placeholder: `请输入${searchState.selectValue.label}`
	};
});

const watchStop = watch(
	() => props.searchQuery,
	() => {
		if (!props.searchQuery[searchState.selectValue.value]) {
			searchState.inputValue = '';
		}
	}
);

const UpdateSearchQuery = (value = ''): void => {
	const newSearchQuery = reactive({
		...props.searchQuery,
		[searchState.selectValue.value]: value
	});

	emits('update:searchQuery', newSearchQuery);
};

const ChangeSelect = (currentOpt: any): void => {
	UpdateSearchQuery();
	searchState.selectValue = { label: currentOpt.label, value: currentOpt.value };
};

const Search = (): void => {
	UpdateSearchQuery(searchState.inputValue);
	nextTick(() => emits('search'));
};
onUnmounted(() => {
	watchStop();
});
</script>

<style lang="less">
.global-condition-search {
	.search-btn-wrap {
		width: 46px;
		height: 38px;
		border: 1px solid @borderColor02;
		border-top-right-radius: 6px;
		border-bottom-right-radius: 6px;
		line-height: 36px;
		text-align: center;
		background-color: @white;

		&:hover {
			border-color: #408bf5;
			cursor: pointer;
		}
	}

	.ant-select-dropdown {
		padding: 4px !important;
	}

	.ant-select-arrow {
		color: @text02;
	}
}
</style>
